package benny.ApkposStore.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import benny.ApkposStore.R;
import benny.ApkposStore.R.string;
import benny.ApkposStore.Adapter.FloorAdapter;
import benny.ApkposStore.Adapter.FloorAdapter.FloorHolder;
import benny.ApkposStore.Adapter.RoomAdapter;
import benny.ApkposStore.Adapter.RoomAdapter.ViewHolder;
import benny.ApkposStore.Service.DishprintService;
import benny.ApkposStore.Xml.turnlistContentHandler;
import benny.ApkposStore.db.ConfigDBHelper;
import benny.ApkposStore.db.DBHelper;
import benny.ApkposStore.model.Floor;
import benny.ApkposStore.model.Room;
import benny.ApkposStore.model.Turndate;
import benny.ApkposStore.utils.ApkConfigdbUntils;
import benny.ApkposStore.utils.ApkConstant;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.FileUtils;

//import com.tencent.elife.asyn.BaseManager;
//import com.tencent.elife.asyn.Command;
//import com.tencent.elife.asyn.DataResponse;

public class RoomtableActivity extends Activity {
	private SQLiteDatabase db;
	private Context dbcm;
	private List<Floor> floorlist;
	private Button returnButton = null;
	private Button manageButton = null;
	private final int floorbtn_widthpx = 93;
	private final int turn_heightpx = 19;
	private final int room_heightpx = 98;
	private final int verticalSpacing = 6;
	private final int floorSpacing = 2;
	private final int PLAYTAG = 1;
	private final int TIMETAG = 2;
	private final int PLAYINT = 5;
	private int floorbtndown = -1;
	private int floorSpacingdip;
	private int floorbtn_widthdip;
	private int floorflingwidth;
	private int verticalSpacingdp;
	private int floorview_width;
	private int room_heightdip;
	private int turnlistview_height;
	private int turn_heightdip;
	private int roomflingwidth;
	private float turn_total = 0;
	private int roomview_height;
	private FloorAdapter floorAdapter = null;
	private ImageView playImageView = null;
	private Button floorlast = null;
	private Button floornext = null;
	private Button roomlast = null;
	private Button roomnext = null;
	private Button roomall = null;
	private Button roomspare = null;
	private Button roomusing = null;
	private Button roompaying = null;
	private String xml = null;
	private HorizontalScrollView floorscrollview = null;
	private ScrollView roomscrollview = null;
	private List<Room> roomlist = null;
	private List<Turndate> turnlist = null;
	private GridView roomGridView = null;
	private GridView floorvGridView = null;
	private ListView turnlistView = null;
	// private TextPaint tp = null;
	private FileInputStream read = null;
	private StringReader xmlread = null;
	private int count_drawble = 0; // 总共的图片大小
	// private int cur_index = 0; // 当前图片位置
	private int Anim_index = 0;// 动画编号
	private Timer playImagetimer = null;
	private SimpleAdapter turnAdapter = null;
	private BitmapDrawable[] imgs = null;
	private String[] imgspath = null;
	private TextView timetext = null;
	private TextView turnlist_title = null;
	private TextView title_text = null;
	private TextView turn_totaltext = null;
	// private SpannableString text_Spannable = null;
	private ArrayList<Animation> anims = new ArrayList<Animation>();// 动画
	// private String SDCardRoot;
	public String roomstate = "all";
	public String floorstate = "all";
	public int floorstate_int;
	private RoomAdapter roomAdapter = null;
	private Resources resources;
	private AlertDialog.Builder builder = null;
	// //长按弹出房台操作界面组件
	private TextView roomselect = null;
	private Button changeroom = null; // 按钮组件
	private PopupWindow operateroomwin = null; // 弹出窗口
	private View operateroomView = null; // 保存弹出窗口布局
	private FileUtils imagesfile = null;
	private SimpleDateFormat dateformat;
	private TextView username_text;
	private SQLiteDatabase configdb;
	static HashMap<String, String> roomstate_map = null;

	// /////////////
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ApkUntils.fullscreen(this);
		setContentView(R.layout.roomtable);
		dbcm=RoomtableActivity.this;				
		// DatabaseHelper helper = new
		// DatabaseHelper(RoomtableActivity.this,"shop_config.db");
		// configdb = helper.getReadableDatabase();
		dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		returnButton = (Button) findViewById(R.id.Return);
		manageButton = (Button) findViewById(R.id.manage);
		builder = new Builder(RoomtableActivity.this);
		returnButton.setOnClickListener(new returnButtonListener());
		manageButton.setOnClickListener(new manageButtonListener());
		username_text = (TextView) findViewById(R.id.username_text);
		username_text.setText(Apkglobal.getrealname());
		timetext = (TextView) findViewById(R.id.timetext);
		title_text = (TextView) findViewById(R.id.titletext);
		turnlist_title = (TextView) findViewById(R.id.turnlisttitle);
		Intent intent = new Intent();
		intent.setClass(RoomtableActivity.this, DishprintService.class);
		startService(intent);// 启动打印任务检测
		// DataManager.instance().init(getApplicationContext());
		/*
		 * // 创建一个 SpannableString对象 text_Spannable = new
		 * SpannableString(Apkconstant.roomtitle); text_Spannable.setSpan(new
		 * StyleSpan(android.graphics.Typeface.ITALIC), 0,
		 * Apkconstant.roomtitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //
		 * 斜体 title_text.setText(text_Spannable);
		 * title_text.setMovementMethod(LinkMovementMethod.getInstance());
		 * text_Spannable = new SpannableString(Apkconstant.turnlisttitle);
		 * text_Spannable.setSpan(new
		 * StyleSpan(android.graphics.Typeface.ITALIC), 0,
		 * Apkconstant.turnlisttitle.length(),
		 * Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 斜体
		 * turnlist_title.setText(text_Spannable);
		 * turnlist_title.setMovementMethod(LinkMovementMethod.getInstance());
		 */
		// 启动播放图片timer
		// imgAdapter = new imageplayAdapter(this);
		imagesfile = new FileUtils();
		imgspath = imagesfile.getimgFilespath("Images/");// 获取SD上Images文件夹下的图片
		if (imgspath != null) {
			initAnimation();
			count_drawble = imgspath.length;
			playImageView = (ImageView) findViewById(R.id.playimgs);
			playImagetimer = new Timer("playImage");
		//	playImagetimer.scheduleAtFixedRate(palyimgtask, 100, 1000);
			playImagetimer.schedule(palyimgtask, 100, 2000);
		}

		// 显示交班数据
		turnlistView = (ListView) findViewById(R.id.turnListview);
		turnlistView.setDrawSelectorOnTop(false);
		turnlistView.setBackgroundColor(R.color.grid_line);
		turnlistView.setSelector(R.color.transparent);
		updateturndateAdapter();
		turn_heightdip = ApkUntils.convertPX2DIP(this, turn_heightpx
				* ApkUntils.getPixelsintH(this));
		turnlistview_height = turn_heightdip * turnAdapter.getCount();
		resources = getResources();
		turnlistView.setDivider(resources.getDrawable(R.color.grid_line));
		turnlistView.setDividerHeight(ApkUntils.convertPX2DIP(this,
				1 * ApkUntils.getPixelsintH(this)));
		if (Apkglobal.getcurrentapiVersion() > 10) {
			turnlistView.setAdapter(turnAdapter);
		}

		ApkUntils.changeviewlayout(turnlistView, 0, turnlistview_height,
				turnAdapter);
		turn_totaltext = (TextView) findViewById(R.id.totalcount);
		turn_totaltext.setText(turn_total + "");
		// ////////////////////////////////////////

		// 设置并显示楼层区域
		floorscrollview = (HorizontalScrollView) findViewById(R.id.floorscrollview);
		floorlast = (Button) findViewById(R.id.floor_last);
		floorlast.setOnClickListener(new floorlastListener());
		floornext = (Button) findViewById(R.id.floor_next);
		floornext.setOnClickListener(new floornextListener());
		// 绑定房台状态按钮监听事件
		roomall = (Button) findViewById(R.id.room_all);
		roomall.setOnClickListener(new roomstateListener());
		roomspare = (Button) findViewById(R.id.room_spare);
		roomspare.setOnClickListener(new roomstateListener());
		roomusing = (Button) findViewById(R.id.room_using);
		roomusing.setOnClickListener(new roomstateListener());
		roompaying = (Button) findViewById(R.id.room_paying);
		roompaying.setOnClickListener(new roomstateListener());

		floorvGridView = (GridView) findViewById(R.id.floorGridview);
		floorbtn_widthdip = ApkUntils.convertPX2DIP(this, floorbtn_widthpx
				* ApkUntils.getPixelsintW(this));
		floorSpacingdip = ApkUntils.convertPX2DIP(this, floorSpacing
				* ApkUntils.getPixelsintW(this));
		/*
		 * floorvGridView.setColumnWidth(floorbtn_widthdip);
		 * floorvGridView.setHorizontalSpacing(floorSpacingdip);
		 * floorvGridView.setNumColumns(floorAdapter.getCount());
		 * floorvGridView.setGravity(Gravity.CENTER);
		 * floorvGridView.setPadding(1, 0, 0, 0);
		 * floorvGridView.setSelector(R.color.transparent); floorview_width =
		 * (floorbtn_widthdip + floorSpacingdip) floorAdapter.getCount();
		 * floorflingwidth = floorbtn_widthdip * 5;
		 * ApkUntils.changeviewlayout(floorvGridView, floorview_width, 0,
		 * floorAdapter);
		 */
		floorvGridView.setOnItemClickListener(new floorstateListener());
		// /////////////////////////////////////////////////////

		// 设置并显示房台区域
		roomscrollview = (ScrollView) findViewById(R.id.roomscrollview);
		roomlast = (Button) findViewById(R.id.room_last);
		roomlast.setOnClickListener(new roomlastListener());
		roomnext = (Button) findViewById(R.id.room_next);
		roomnext.setOnClickListener(new roomnextListener());

		// updateroomAdapter();
		// ////////////////////////////////////////
		roomGridView = (GridView) findViewById(R.id.roomGridview);
		// room_heightdip = ApkUntils.convertPX2DIP(this, room_heightpx);
		room_heightdip = ApkUntils.convertPX2DIP(this, room_heightpx
				* ApkUntils.getPixelsintH(this));
		System.out.println(ApkUntils.getPixelsintH(this));
		// verticalSpacingdp = ApkUntils.convertPX2DIP(this, verticalSpacing);
		verticalSpacingdp = ApkUntils.convertPX2DIP(this, verticalSpacing
				* ApkUntils.getPixelsintH(this));
		roomGridView.setNumColumns(5);
		roomGridView.setGravity(Gravity.FILL_VERTICAL);
		roomGridView.setSelector(R.color.transparent);
		roomGridView.setVerticalSpacing(verticalSpacingdp);
		roomflingwidth = room_heightdip * 5;
		/*
		 * roomview_height = room_heightdip (int)
		 * Math.ceil(roomAdapter.getCount() / 5.0);
		 * 
		 * ApkUntils.changeviewlayout(roomGridView, 0, roomview_height,
		 * roomAdapter);
		 */
		roomGridView.setOnItemClickListener(new roomitemListener());
		roomGridView.setOnItemLongClickListener(new roomitemlongListener());

	}

	// 初始化动画
	private void initAnimation() {
		Animation anim1 = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.rotate1);
		Animation anim2 = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.scale1);
		Animation anim3 = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.translate1);
		Animation anim4 = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.alpha1);

		anims.add(anim1);
		anims.add(anim2);
		anims.add(anim3);
		anims.add(anim4);

	}

	private TimerTask palyimgtask = new TimerTask() {
		private int cur_index = 0;
		private int timeint = 0;

		@Override
		public void run() {
			if (timeint % PLAYINT == 0) {
				cur_index = cur_index % count_drawble; // 图片区间[0,count_drawable)
				// Anim_index = r.nextInt(anims.size());// 随机找动画
				Anim_index = 3;
				// 将动画和图片的编号作为参数传送过去
				Message msg1 = mhandler.obtainMessage(PLAYTAG, cur_index,
						Anim_index);
				mhandler.sendMessage(msg1);
				cur_index++;
			}
			Message msg2 = mhandler.obtainMessage(TIMETAG, timeint, 0);
			mhandler.sendMessage(msg2);
			timeint++;

		}
	};

	private Handler mhandler = new Handler() {

		private Bitmap bitmap;
		private BitmapDrawable imgplay;

		public void handleMessage(Message msg) {

			if (msg.what == PLAYTAG) {
				// 更改播放图片
				if (bitmap != null) {
					bitmap.recycle();
				}

				bitmap = BitmapFactory.decodeFile(imgspath[msg.arg1]);
				imgplay = new BitmapDrawable(bitmap);
				playImageView.setBackgroundDrawable(imgplay);
				playImageView.startAnimation(anims.get(msg.arg2));

				// Animation zoomin =
				// AnimationUtils.loadAnimation(getApplicationContext(),
				// R.anim.zoomout);
				// playImageView.startAnimation(zoomin);
			}
			if (msg.what == TIMETAG) {
				// 获取系统时间
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
				String date = sdf.format(new java.util.Date());
				timetext.setText(date);
			}
		}
	};

	// 解析turn实体类XML
	private List<Turndate> turnparse(StringReader readss, InputStream readin) {

		SAXParserFactory saxparsefactory = SAXParserFactory.newInstance();
		List<Turndate> turndates = new ArrayList<Turndate>();
		try {
			XMLReader xmlreader = saxparsefactory.newSAXParser().getXMLReader();
			turnlistContentHandler turnlistContentHandler = new turnlistContentHandler(
					turndates);
			xmlreader.setContentHandler(turnlistContentHandler);
			if (readss != null) {
				xmlreader.parse(new InputSource(readss));
			} else
				xmlreader.parse(new InputSource(readin));
			for (Iterator<Turndate> iterator = turndates.iterator(); iterator
					.hasNext();) {
				Turndate turndate = (Turndate) iterator.next();
				// System.out.println("-----" + room);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return turndates;

	}

	// 创建一个 RoomAdapter
	private RoomAdapter buildRoomAdapter(List<Room> roomlist) {
		roomstate_map=ApkConfigdbUntils.updateroomstate(db, dbcm);
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		for (Iterator<Room> iterator = roomlist.iterator(); iterator.hasNext();) {
			Room room = (Room) iterator.next();
			HashMap<String, Object> map = new HashMap<String, Object>();
			String Rstate="0";
			String Payment="0";
			String Time="";
			if (roomstate_map.get(room.getAlias_id())!=null) {
				Rstate = roomstate_map.get(room.getAlias_id()) ;
			}
			if (roomstate_map.get(room.getAlias_id()+"P")!=null) {
				Payment=roomstate_map.get(room.getAlias_id()+"P");
				float ddd = (float) (Float.parseFloat(Payment)*0.01);
				Payment=ApkUntils.convertFloat(ddd+"", 1);
			}
			else {
				Payment="0";
			}
			if (roomstate_map.get(room.getAlias_id()+"T")!=null) {
				
				Time=roomstate_map.get(room.getAlias_id()+"T");
				Time=Time.substring(Time.indexOf(" ") + 1, Time.length());
			}
			String Fstate = room.getFloor_id() + "";
			map.put("room_name", room.getName());
			map.put("room_id", room.getAlias_id());
			map.put("room_state", Rstate);
			map.put("room_floor", room.getFloor_id());
			map.put("price_type", room.getPrice_type());
			if (roomstate_map.get(room.getAlias_id()+"N")!=null) {
				map.put("room_cnt", roomstate_map.get(room.getAlias_id()+"N"));	
			}
			else {
				map.put("room_cnt", "0");		
			}
			

			if (floorstate.equals("all")) {
				if (roomstate.equals("all")) {

					if (Rstate.equals("1") || Rstate.equals("3")) {
						map.put("icon", R.drawable.selector_room_yellow);
					} else if (Rstate.equals("6")) {
						map.put("icon", R.drawable.selector_room_blue);
					} else {
						map.put("icon", R.drawable.selector_room_green);
					}

					// 测试数据，金额和时间
					if (!Rstate.equals("0")) {
						map.put("room_time", Time);
						map.put("room_payment",Payment);
					} else {
						map.put("room_time", "0");
						map.put("room_payment", "0");
					}
					// //////
					list.add(map);
				} else {
					if (Rstate.equals(roomstate)) {

						if (Rstate.equals("1") || Rstate.equals("3")) {
							map.put("icon", R.drawable.selector_room_yellow);
						} else if (Rstate.equals("6")) {
							map.put("icon", R.drawable.selector_room_blue);
						} else {
							map.put("icon", R.drawable.selector_room_green);
						}

						if (!Rstate.equals("0")) {
							map.put("room_time", Time);
							map.put("room_payment",Payment);
						} else {
							map.put("room_time", "0");
							map.put("room_payment", "0");
						}
						// //////
						list.add(map);
					}

				}

			} else {
				if (Fstate.equals(floorstate)) {
					if (roomstate.equals("all")) {

						if (Rstate.equals("1") || Rstate.equals("3")) {
							map.put("icon", R.drawable.selector_room_yellow);
						} else if (Rstate.equals("6")) {
							map.put("icon", R.drawable.selector_room_blue);
						} else {
							map.put("icon", R.drawable.selector_room_green);
						}
						// 测试数据，金额和时间
						if (!Rstate.equals("0")) {
							map.put("room_time", Time);
							map.put("room_payment",Payment);
						} else {
							map.put("room_time", "0");
							map.put("room_payment", "0");
						}
						// //////
						list.add(map);
					} else {
						if (Rstate.equals(roomstate)) {
							if (Rstate.equals("1") || Rstate.equals("3")) {
								map.put("icon", R.drawable.selector_room_yellow);
							} else if (Rstate.equals("6")) {
								map.put("icon", R.drawable.selector_room_blue);
							} else {
								map.put("icon", R.drawable.selector_room_green);
							}
							// 测试数据，金额和时间
							if (!Rstate.equals("0")) {
								map.put("room_time", Time);
								map.put("room_payment", Payment);
							} else {
								map.put("room_time", "0");
								map.put("room_payment", "0");
							}

							// //////
							list.add(map);
						}

					}
				}

			}

		}
		// 创建一个RoomAdapter对象
		System.out.println(list);
		RoomAdapter roomadapter = new RoomAdapter(this, list);
		return roomadapter;

	}

	// 创建一个 floorAdapter
	private FloorAdapter buildfloorAdapter(List<Floor> floorlist) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		map.put("floor_name", "全部");
		map.put("floor_id", "all");
		list.add(map);
		for (Iterator<Floor> iterator = floorlist.iterator(); iterator
				.hasNext();) {
			Floor floor = (Floor) iterator.next();
			map = new HashMap<String, Object>();
			map.put("floor_name", floor.getFloor_name());
			map.put("floor_id", floor.getId());
			list.add(map);

		}

		// 创建一个floorAdapter对象
		FloorAdapter floorAdapter = new FloorAdapter(this, list);
		return floorAdapter;

	}

	// 创建一个Turndate SimpleAdapter
	private SimpleAdapter buildturnAdapter(List<Turndate> turnlist) {
		turn_total = 0;
		int i = 0;
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		for (Iterator<Turndate> iterator = turnlist.iterator(); iterator
				.hasNext();) {
			Turndate turndate = (Turndate) iterator.next();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("turn_id", turndate.getId());
			map.put("turn_item", turndate.getTurn_item());
			map.put("turn_num", turndate.getTurn_num());
			map.put("turn_total", turndate.getTurn_total());
			turn_total = turn_total
					+ Float.parseFloat(turndate.getTurn_total());
			list.add(map);
			i++;
		} // 创建一个SimpleAdapter对象

		// 记录不够6条的时候加满到6
		while (i <= 5) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("turn_id", null);
			map.put("turn_item", null);
			map.put("turn_num", null);
			map.put("turn_total", null);
			list.add(map);
			i++;
		}

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
				R.layout.turnlistitem, new String[] { "turn_id", "turn_item",
						"turn_num", "turn_total" }, new int[] { R.id.turnitem1,
						R.id.turnitem2, R.id.turnitem3, R.id.turnitem4 });

		return simpleAdapter;

	}

	// 弹起所有房台状态按钮
	private void roomstatebtn_up() {
		Button btn = null;
		btn = (Button) findViewById(R.id.room_spare);
		btn.setBackgroundResource(R.drawable.selector_btn_green);
		btn = (Button) findViewById(R.id.room_using);
		btn.setBackgroundResource(R.drawable.selector_btn_yellow);
		btn = (Button) findViewById(R.id.room_paying);
		btn.setBackgroundResource(R.drawable.selector_btn_blue);
		btn = (Button) findViewById(R.id.room_all);
		btn.setBackgroundResource(R.drawable.selector_btn_red);
	}

	// 创建一个播放广播监听
	class playimageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			String msgstring = arg1.getStringExtra("imageindex");
			int msgint = Integer.parseInt(msgstring);
			if (msgint > 0) {
				playImageView.setBackgroundResource(msgint);
			}

		}

	}

	// 创建房台状态Listener
	class roomstateListener implements OnClickListener {
		private Button btn = null;

		@Override
		public void onClick(View v) {
			roomstatebtn_up();
			// TODO Auto-generated method stub
			switch (v.getId()) {

			case R.id.room_all:
				roomstate = "all";
				break;
			case R.id.room_spare:
				roomstate = "0";
				break;
			case R.id.room_using:
				roomstate = "3";
				break;
			case R.id.room_paying:
				roomstate = "6";
				break;
			default:
				break;
			}
			// updateroomAdapter();
			roomAdapter = buildRoomAdapter(roomlist);
			updateroomGridView();
			btn = (Button) findViewById(v.getId());
			btn.setBackgroundResource(R.drawable.btn_select);
		}

	}

	// 通过http从服务器上下载并解析jiaob数据
	private void updateturndateAdapter() {
		FileUtils turnfileUtils = new FileUtils();
		if (turnfileUtils.isFileExist("turn.xml", "Date/")) {
			try {
				// 通过http从服务器上下载并解析楼层数据
				File file = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath() + File.separator + "Date/turn.xml");
				read = new FileInputStream(file);
				turnlist = turnparse(null, read);
				// System.out.println(turnlist);
				turnAdapter = buildturnAdapter(turnlist);
				// //////////////////////////////////////////
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		} else {
			try {
				// 通过http从服务器上下载并解析房台数据
				xml = ApkUntils.downloadxml(ApkConstant.BaseUrl + "turn.xml");
				xmlread = new StringReader(xml);
				turnlist = turnparse(xmlread, null);
				turnAdapter = buildturnAdapter(turnlist);
				// //////////////////////////////////////////
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}

	}

	// 通过http从服务器上下载并解析房台数据
	/*
	 * private void updateroomAdapter() { FileUtils roomfileUtils = new
	 * FileUtils(); if (roomfileUtils.isFileExist("room.xml", "Date/")) { try {
	 * // 通过http从服务器上下载并解析楼层数据 File file = new
	 * File(Environment.getExternalStorageDirectory() .getAbsolutePath() +
	 * File.separator + "Date/room.xml"); read = new FileInputStream(file);
	 * roomlist = roomparse(null, read); roomAdapter =
	 * buildRoomAdapter(roomlist); // //////////////////////////////////////////
	 * } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
	 * } else { try { // 通过http从服务器上下载并解析房台数据 xml =
	 * ApkUntils.downloadxml(Apkconstant.BaseUrl + "room.xml"); xmlread = new
	 * StringReader(xml); roomlist = roomparse(xmlread, null); roomAdapter =
	 * buildRoomAdapter(roomlist); // //////////////////////////////////////////
	 * } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
	 * 
	 * }
	 * 
	 * }
	 */

	// 刷新房台界面
	public void updateroomGridView() {
		roomview_height = room_heightdip
				* (int) Math.ceil(roomAdapter.getCount() / 5.0);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			roomGridView.setAdapter(roomAdapter);
		}
		ApkUntils.changeviewlayout(roomGridView, 0, roomview_height,
				roomAdapter);
		// roomAdapter.notifyDataSetChanged();
	}

	// 创建room点击Listener
	class roomitemListener implements OnItemClickListener {
		ViewHolder holder = null;
		String room_id = null;
		String orderid = null;
		String room_name = null;
		String date = null;
		String orderint ="";
		Cursor cursor=null;
		private int price_type;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			holder = (ViewHolder) view.getTag();
			room_id = holder.roomtitle.getHint().toString();
			room_name = holder.roomtitle.getText().toString();
			price_type = holder.price_type;
			try {
				if (db == null || !db.isOpen()) {
					db = DBHelper.getDatabase(dbcm,0);
				}
				cursor = db
						.query("apkpos_orders_new",
								new String[] { "orderid,table_num,table_extent,people_num,openuser" },
								"table_num=? and room_state<=6",
								new String[] { room_id }, null, null, null);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
            if (cursor==null) {
				return;
			}

			System.out.println(cursor.getCount());
			if (cursor.getCount() == 0) {
//			     SQLiteDatabase mdb = DBHelper.getDatabase(dbcm); 
//				Cursor cursornew = mdb.query("apkpos_orders_new",
//						new String[] { "ifnull(max(orderint),0) as aaa" },
//						null, null, null, null, null);
//				
//				if (cursornew == null) {
//					orderint = 0;
//				} else {
//					while (cursornew.moveToNext()) {
//						orderint = cursornew.getInt(cursornew.getColumnIndex("aaa"));
//
//					}
//
//				}
//				cursornew.close();
//				cursor.close();

				date = dateformat.format(new java.util.Date());
				SimpleDateFormat dateformatorder = new SimpleDateFormat(
						"yyyyMMdd");
				String dateorder = dateformatorder.format(new java.util.Date());
//				String dateold = ApkUntils.ReadSharedPreferences(RoomtableActivity.this, "odnotable", "date");
//				
//				if (!dateorder.equals(dateold)) {
//					ApkUntils.WriteSharedPreferences(RoomtableActivity.this, "odnotable", "date", dateorder);				
//					orderint = 1;
//					ApkUntils.WriteSharedPreferences(RoomtableActivity.this, "odnotable", "id", orderint+"");
//				} else {
//					String idstr = ApkUntils.ReadSharedPreferences(RoomtableActivity.this, "odnotable", "id");
//					if ((!idstr.equals(""))&(idstr!=null)) {
//						orderint=Integer.parseInt(idstr);	
//					}
//					else {
//						orderint=0;
//					}
//					orderint = orderint + 1;
//					ApkUntils.WriteSharedPreferences(RoomtableActivity.this, "odnotable", "id", orderint+"");
//				}
//
//				String orderstr = orderint + "";
//				while (orderstr.length() < 4) {
//					orderstr = "0" + orderstr;
//				}
//
//				orderid = dateorder + orderstr + Apkglobal.getposid();
//				System.out.println(orderid + "   " + orderint);
//				System.out.println("Apkglobal.getposid():"
//						+ Apkglobal.getposid());
				orderid=ApkUntils.getOdno_var_new(RoomtableActivity.this,dateorder);
				orderint= ApkUntils.ReadSharedPreferences(RoomtableActivity.this, "odnotable", "id");
				try {
					if (db == null || !db.isOpen()) {
						db = DBHelper.getDatabase(dbcm,1);
					}
					db.execSQL("insert into apkpos_orders_new(orderid,orderint,table_num,table_extent,people_num,dish_total,"
							+ "room_state,order_state,open_time,dic_rate,openuser)"
							+ " values ('"
							+ orderid
							+ "',"
							+ orderint
							+ ","
							+ room_id
							+ ",'',1,0,3,0,'"
							+ date
							+ "',100,'"
							+ Apkglobal.getrealname() + "')");
				} catch (SQLiteException e) {
					Log.e("apkpos_orders_new",
							"insert apkpos_orders_new error:" + e.getMessage());
				}

			} else {
				
				if (cursor.getCount()>1) {

					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putString("room_name", room_name);
					bundle.putString("room_id",room_id);
					bundle.putInt("price_type", price_type);
					intent.putExtras(bundle);
					intent.setClass(RoomtableActivity.this, RoomListActivity.class);			
					startActivity(intent);
					return;
				}
				else {
					cursor.moveToFirst();
					orderid = cursor
							.getString(cursor.getColumnIndex("orderid"));
				}
				
			}
			cursor.close();
			// holder.roomtitle.setTextColor(R.color.white);
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("orderid", orderid);
			bundle.putString("room_name", room_name);
			bundle.putString("room_id", room_id);
			bundle.putInt("people_num", 1);
			bundle.putInt("price_type", price_type);
			intent.putExtras(bundle);
			intent.setClass(RoomtableActivity.this, DishordersActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
			finish();
		}
	}
	
	

	// 创建room长按Listener
	class roomitemlongListener implements OnItemLongClickListener {
		ViewHolder holder = null;

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			holder = (ViewHolder) arg1.getTag();
			int cnt=holder.cnt;
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("room_name", holder.roomtitle.getText().toString());
			bundle.putString("room_id", holder.roomtitle.getHint().toString());
			bundle.putInt("price_type", holder.price_type);
			intent.putExtras(bundle);
			if (cnt>1) {			
				intent.setClass(RoomtableActivity.this, RoomListActivity.class);			
				startActivity(intent);
				
			}
			else {
				
				intent.setClass(RoomtableActivity.this, RoomoperateActivity.class);			
				startActivity(intent);

			}
			
			//ApkUntils.openActivityAnim(RoomtableActivity.this, 4);

//			LayoutInflater inflater = LayoutInflater
//					.from(RoomtableActivity.this); // 取得LayoutInflater对象
//			operateroomView = inflater.inflate(R.layout.roomoperate, null); // 读取布局管理器
//			operateroomwin = new PopupWindow(operateroomView, 300, 240, true); // 实例化PopupWindow
//			changeroom = (Button) operateroomView
//					.findViewById(R.id.roomselectclose); // 取得组件
//			roomselect = (TextView) operateroomView
//					.findViewById(R.id.roomselecttxt); // 取得组件
//			roomselect.setText("你选择的房台是：" + holder.roomtitle.getText());
//			changeroom.setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					RoomtableActivity.this.operateroomwin.dismiss(); // 关闭弹出窗口
//				}
//			});
//			RoomtableActivity.this.operateroomwin.showAtLocation(
//					RoomtableActivity.this.roomGridView, Gravity.CENTER, 0, 0); // 显示弹出窗口

			return false;
		}

	}

	// 创建对话框函数
	@SuppressWarnings("unused")
	private void dialog(AlertDialog.Builder builder, Integer icon) {

		builder.setMessage("aaa");
		builder.setTitle("bbb");
		builder.setIcon(icon);
		builder.setPositiveButton(string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						Intent intent = new Intent();
						intent.setClass(RoomtableActivity.this,
								DishordersActivity.class);
						startActivity(intent);// 这里写OK事件
						finish();
					}

				});
		builder.setNegativeButton(string.cancal,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						// 这里写cancal事件
					}

				});

		builder.create().show();

	}

	// 创建楼层状态Listener
	class floorstateListener implements OnItemClickListener {
		FloorHolder floorholder = null;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			if (floorbtndown != position) {
				if (floorbtndown != -1) {
					floorholder = (FloorHolder) parent.getChildAt(floorbtndown)
							.getTag();
					floorholder.floortitle
							.setBackgroundResource(R.drawable.selector_btn_floor);
				}
				floorholder = (FloorHolder) view.getTag();
				floorholder.floortitle
						.setBackgroundResource(R.drawable.btn_select);
				floorbtndown = position;
			}

			if (position == 0) {
				floorstate = "all";
			} else {
				Floor floor = floorlist.get(position - 1);
				floorstate = floor.getId() + "";

			}

			// updateroomAdapter();
			roomAdapter = buildRoomAdapter(roomlist);
			updateroomGridView();
		}

	}

	// /////////////////////////////
	// 上一个房间监听器
	class roomlastListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			roomscrollview.fling(-1 * roomflingwidth);
		}

	}

	// 下一个房间监听器
	class roomnextListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			roomscrollview.fling(roomflingwidth);
		}

	}

	// 上一个楼层监听器
	class floorlastListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			floorscrollview.fling(-1 * floorflingwidth);
		}

	}

	// 下一个楼层监听器
	class floornextListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			floorscrollview.fling(floorflingwidth);
		}

	}

	// 管理按钮监听器
	class manageButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
			/*
			 * Uri uri = Uri.parse("geo:38.899533,-77.036476"); Intent it = new
			 * Intent(Intent.ACTION_VIEW,uri); startActivity(it);
			 */
		}

		/*
		 * private void checkNetworkInfo() { ConnectivityManager conMan =
		 * (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		 * // mobile 3G Data Network State mobile = conMan.getNetworkInfo(
		 * ConnectivityManager.TYPE_MOBILE).getState(); //
		 * txt3G.setText(mobile.toString()); // wifi State wifi =
		 * conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); //
		 * txtWifi.setText(wifi.toString()); // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态
		 * 则进入Network Setting界面 由用户配置网络连接 if (mobile == State.CONNECTED ||
		 * mobile == State.CONNECTING) return; if (wifi == State.CONNECTED ||
		 * wifi == State.CONNECTING) return; startActivity(new
		 * Intent(Settings.ACTION_WIRELESS_SETTINGS)); // 进入无线网络配置界面 //
		 * startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //
		 * 进入手机中的wifi网络设置界面 } }
		 */

	}

	// 返回按钮监听器
	class returnButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setClass(RoomtableActivity.this, ApkposStoreActivity.class);
			startActivity(intent);
			ApkUntils.openActivityAnim(RoomtableActivity.this, 0);
			finish();
		}

	}

	@Override
	public void onDestroy() {
		if (playImagetimer != null) {
			playImagetimer.cancel();
		}

		/*
		 * for (int i = 0; i < imgspath.length - 1; i++) { if
		 * (!(imgs[i].getBitmap()).isRecycled()) {// 先判断图片是否已释放了
		 * (imgs[i].getBitmap()).recycle(); // System.out.println("recycle"); }
		 * }
		 */
		System.gc(); // 回收系统资源
		super.onDestroy();
		// DataManager.instance().release();
	}

	private void updateresponse() {
		// //获取房台

		configdb = ConfigDBHelper.getDatabase(dbcm,"shop_config.db",0);
		if (Apkglobal.getroomlist() != null) {
			roomlist = Apkglobal.getroomlist();
			roomAdapter = buildRoomAdapter(roomlist);
			updateroomGridView();
		} else {
			roomlist = ApkConfigdbUntils.updateroomlist(configdb,
					dbcm);
			Apkglobal.setroomlist(roomlist);
			roomAdapter = buildRoomAdapter(roomlist);
			updateroomGridView();
		}

		// //获取楼层
		if (Apkglobal.getfloorlist() != null) {
			floorlist = Apkglobal.getfloorlist();
			showfloorview();
		} else {
			floorlist = ApkConfigdbUntils.updatefloorlist(configdb,
					dbcm);
			Apkglobal.setfloorlist(floorlist);
			showfloorview();
		}
		configdb.close();

	}

	private void showfloorview() {
		floorAdapter = buildfloorAdapter(floorlist);
		floorvGridView.setColumnWidth(floorbtn_widthdip);
		floorvGridView.setHorizontalSpacing(floorSpacingdip);
		floorvGridView.setNumColumns(floorAdapter.getCount());
		floorvGridView.setGravity(Gravity.CENTER);
		floorvGridView.setPadding(1, 0, 0, 0);
		floorvGridView.setSelector(R.color.transparent);
		floorview_width = (floorbtn_widthdip + floorSpacingdip)
				* floorAdapter.getCount();
		floorflingwidth = floorbtn_widthdip * 5;
		if (Apkglobal.getcurrentapiVersion() > 10) {
			floorvGridView.setAdapter(floorAdapter);
		}
		ApkUntils.changeviewlayout(floorvGridView, floorview_width, 0,
				floorAdapter);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateresponse();
	//	db = DBHelper.getDatabase(dbcm);
	}

}
